package com.conversationboard.controller;

import java.io.IOException;
import java.security.Principal;
import java.sql.SQLException;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.controller.debug.ServletDebugInfo;
import com.conversationboard.logger.Logger;
import com.conversationboard.model.Message;
import com.conversationboard.model.Role;
import com.conversationboard.model.User;
import com.conversationboard.security.EncryptedKey;
import com.conversationboard.security.EncryptionException;

@WebServlet(name = "AdminDeleteMessageControllerServlet", urlPatterns = "/Admin/AdminDeleteMessageControllerServlet")
public class AdminDeleteMessageControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 5342760547890757784L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		int boardId = Integer.parseInt(request.getParameter("boardid"));
		int threadId = Integer.parseInt(request.getParameter("threadid"));
		int messageId = Integer.parseInt(request.getParameter("messageid"));

		Principal principal = request.getUserPrincipal();

		if (principal == null) {
			/* Can't get the user; go back to the page you came from */
			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/thread.jsp?boardid=" + boardId + "&threadid=" + threadId + "&amp;messageid=" + messageId);
			dispatcher.forward(request, response);
			return;
		}

		String userId = principal.getName();

		try {

			User user = User.get(userId);
			Role role = user.getRole();

			String key = request.getParameter("key");
			EncryptedKey encryptedKey = new EncryptedKey();

			if (!encryptedKey.isValid(key, user.getLoginId())) {
				Logger.log(new Date(), "Part 1 of error: " + this.getClass().getName(), user);
				String postRequest = ServletDebugInfo.getRawRequest(request);
				Logger.log(new Date(), "Part 2 of error:\n\n" + postRequest, user);
				return;
			}

			/* Does the user have the authority? */
			if (role == Role.SiteAdmin || user.isBoardAdmin(boardId)) {
				Message.delete(user, boardId, threadId, messageId);
			}

			response.sendRedirect(request.getContextPath() + "/ThreadSelectedControllerServlet?boardid=" + boardId + "&threadid=" + threadId);

		} catch (SQLException e) {
			throw new ServletException(e);
		} catch (EncryptionException e) {
			throw new ServletException(e);
		}
	}

}
